package com.kienbk1910.productmanager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import net.sourceforge.zbar.android.CameraTest.CameraTestActivity;
import net.sourceforge.zbar.android.CameraTest.ZBarConstants;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.w3c.dom.Comment;

import android.app.Activity;
import android.app.AlertDialog;

import android.app.ProgressDialog;
import android.content.ContentValues;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.Toast;

import com.kienbk1910.common.Commom;
import com.kienbk1910.model.Product;
import com.kienbk1910.productmanager.provider.DBHelper;
import com.kienbk1910.productmanager.provider.ProductProvider;

public class MainActivity extends Activity implements OnClickListener {

	public static final int SCANNER_RESULT = 111;
	private ListView productList;
	private ProductAdapter adapter;
	private Button addProduct;
	private Button btnScan;
	private Button makeFile;
	private EditText search;

	Cursor c;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getActionBar().setTitle("Quản lý sản phẩm");
		productList = (ListView) findViewById(R.id.productlist);
		addProduct = (Button) findViewById(R.id.addButton);
		btnScan = (Button) findViewById(R.id.btnScan);
		search = (EditText) findViewById(R.id.editTSearch);

		makeFile = (Button) findViewById(R.id.makeFile);

		addProduct.setOnClickListener(this);
		btnScan.setOnClickListener(this);
		makeFile.setOnClickListener(this);
		showAllBirthdays();

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.aboutme) {
			Intent intent = new Intent(MainActivity.this, AboutMeActivity.class);
			startActivity(intent);
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void showAllBirthdays() {
		// Show all the birthdays sorted by friend's name
		String URL = ProductProvider.URL;
		Uri friends = Uri.parse(URL);
		c = getContentResolver().query(friends, null, null, null, "name");
		adapter = new ProductAdapter(this, c);
		productList.setAdapter(adapter);
		productList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				c.moveToPosition(position);
				Product product = getProduct(c);
				Intent intent = new Intent(MainActivity.this,
						ViewProductActivity.class);
				intent.putExtra(Commom.PRODUCT, product);
				startActivity(intent);
				overridePendingTransition(R.anim.slide_in_right,
						R.anim.slide_out_left);

			}
		});

		search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

				adapter.getFilter().filter(s.toString());

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		adapter.setFilterQueryProvider(new FilterQueryProvider() {

			@Override
			public Cursor runQuery(CharSequence constraint) {
				// TODO Auto-generated method stub
				String URL = ProductProvider.URL;
				Uri friends = Uri.parse(URL);

				c = getContentResolver().query(friends, null,
						"name LIKE '%" + constraint.toString() + "%'", null,
						"name");
				return c;
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.addButton:
			newProuct();
			break;
		case R.id.btnScan:

			Intent intent2 = new Intent(MainActivity.this,
					CameraTestActivity.class);
			startActivityForResult(intent2, SCANNER_RESULT);

			break;
		case R.id.makeFile:
			new makeFileTask().execute();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		/**
		 * Back from scanner view
		 */
		if (requestCode == SCANNER_RESULT) {
			if (resultCode == RESULT_OK) {
				String contents = intent
						.getStringExtra(ZBarConstants.SCAN_RESULT);
				Log.d("kienbk1910", contents);
				String URL = ProductProvider.URL;
				Uri friends = Uri.parse(URL);
				Cursor cursor = getContentResolver().query(friends, null,
						DBHelper.BAR_CODE + " LIKE '" + contents + "'", null,
						"name");
				if (cursor != null) {

					if (cursor.moveToFirst()) {
						Product product = getProduct(cursor);
						Intent intent1 = new Intent(MainActivity.this,
								ViewProductActivity.class);
						intent1.putExtra(Commom.PRODUCT, product);
						startActivity(intent1);
					} else {
						new AlertDialog.Builder(this)
								.setTitle("Xác nhận")
								.setMessage(
										"Không có dữ liệu của sản phẩm, bạn một cập nhật sản phẩm không?")
								.setPositiveButton("Đồng ý",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												// continue with delete
												newProuct();

											}
										})
								.setNegativeButton("Không",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int which) {
												// do nothing
											}
										}).setIcon(R.drawable.ic_launcher)
								.show();
					}
				}

			} else if (resultCode == RESULT_CANCELED) {
				// Handle cancel
				Log.i(MainActivity.class.getSimpleName(), "Handle cancel");
			}
		}

	}

	private Product getProduct(Cursor cursor) {
		Product product = new Product();
		product.setId(cursor.getInt(cursor.getColumnIndex(DBHelper.ID)));
		product.setName(cursor.getString(cursor.getColumnIndex(DBHelper.NAME)));
		product.setManufacturer(cursor.getString(cursor
				.getColumnIndex(DBHelper.MANUFACTURER)));
		product.setCost(cursor.getInt(cursor.getColumnIndex(DBHelper.COST)));
		product.setCount(cursor.getInt(cursor.getColumnIndex(DBHelper.COUNT)));
		product.setBarcode(cursor.getString(cursor
				.getColumnIndex(DBHelper.BAR_CODE)));
		product.setNote(cursor.getString(cursor.getColumnIndex(DBHelper.NOTE)));
		product.setImagePath(cursor.getString(cursor
				.getColumnIndex(DBHelper.IMAGE_PATH)));
		return product;
	}

	public void newProuct() {
		Intent intent = new Intent(MainActivity.this, AddProductActivity.class);
		intent.putExtra(Commom.MODE, Commom.NEW);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
	}

	public boolean data_save_xls() {

		// New Workbook
		Workbook wb = new HSSFWorkbook();
		CellStyle style = wb.createCellStyle();
		CellStyle style1 = wb.createCellStyle();
		CellStyle style2 = wb.createCellStyle();
		DataFormat format = wb.createDataFormat();

		style.setDataFormat(format.getFormat("@"));
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style1.setDataFormat(format.getFormat("@"));
		style1.setAlignment(CellStyle.ALIGN_LEFT);
		style2.setDataFormat(format.getFormat("@"));
		style2.setAlignment(CellStyle.ALIGN_RIGHT);
		// New Sheet
		Sheet sheet1 = null;
		sheet1 = wb.createSheet("sv");

		sheet1.setColumnWidth(0, (15 * 50));
		sheet1.setColumnWidth(1, (15 * 300));
		sheet1.setColumnWidth(2, (15 * 300));
		sheet1.setColumnWidth(3, (15 * 200));
		sheet1.setColumnWidth(4, (15 * 300));
		sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
		// Generate column headings
		// write header

		//style.setFont(font);
		Row row = (Row) sheet1.createRow(0);
		// write id
		Cell cell = row.createCell(0);
		cell.setCellValue("Danh sách sản phẩm");
		cell.setCellStyle(style);
	
		row = (Row) sheet1.createRow(2);
		style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
		style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
		style.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
		style.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
		style1.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
		style1.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
		style1.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
		style1.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
		style2.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
		style2.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
		style2.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
		style2.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
		 cell = row.createCell(0);
		cell.setCellValue("#");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("Tên sản phẩm");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("Nhà sản xuất");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("Số lượng");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("Giá");
		cell.setCellStyle(style);

		int j = 0;
		String URL = ProductProvider.URL;
		Uri friends = Uri.parse(URL);
		Cursor cursor = getContentResolver().query(friends, null, null, null,
				"name");

		if (cursor.moveToFirst()) {
			do {
				row = sheet1.createRow(j + 3);
			cell =row.createCell(0);
			cell.setCellValue(j + 1);
			cell.setCellStyle(style);
			cell=row.createCell(1);
			cell.setCellValue(
						cursor.getString(cursor.getColumnIndex(DBHelper.NAME)));
			
				cell.setCellStyle(style1);
				cell=row.createCell(2);
				cell.setCellValue(
						cursor.getString(cursor
								.getColumnIndex(DBHelper.MANUFACTURER)));
				cell.setCellStyle(style1);
				cell=row.createCell(3);
				cell.setCellValue(
						cursor.getInt(cursor.getColumnIndex(DBHelper.COUNT)));
				cell.setCellStyle(style2);
				cell = row.createCell(4);
				cell.setCellValue(
						Commom.intToStringWithplot(cursor.getInt(cursor
								.getColumnIndex(DBHelper.COST))));
				cell.setCellStyle(style2);
				j++;

			} while (cursor.moveToNext());
		}
		row = sheet1.createRow(j + 4);
		sheet1.addMergedRegion(new CellRangeAddress(j + 4, j + 4, 0, 4));
		row.createCell(0).setCellValue("Ngày cập nhật :"+getTimeSave());


		File folder = new File(Environment.getExternalStorageDirectory()
				+ "/productmanager/danhsach");

		if (!folder.exists()) {
			folder.mkdir();
		}
		boolean success = false;
		File file = new File(folder.getAbsolutePath() + "/danhsach.xls");
		FileOutputStream os = null;

		try {
			os = new FileOutputStream(file);

			wb.write(os);

			os.flush();
			Log.w("FileUtils", "Writing file" + file);
			success = true;
		} catch (IOException e) {
			Log.w("FileUtils", "Error writing " + file, e);
		} catch (Exception e) {
			Log.w("FileUtils", "Failed to save file", e);
		} finally {
			try {
				if (null != os)
					os.close();
			} catch (Exception ex) {
			}
		}
		return success;
	}

	private static String getTimeSave() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"HH:mm:ss dd/MM/yyyy");
		Calendar c = Calendar.getInstance();
		return dateFormat.format(c.getTime());
	}

	class makeFileTask extends AsyncTask<String, String, String> {
		ProgressDialog dialog;

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialog = ProgressDialog.show(MainActivity.this, "",
					"Đang tạo file..");
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			data_save_xls();
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			dialog.dismiss();
			Toast.makeText(MainActivity.this, "Tạo file thành công",
					Toast.LENGTH_SHORT).show();
			super.onPostExecute(result);
		}

	}
}